package com.gxks.lhs.controller.admin;

import com.gxks.lhs.DTO.LoginDTO;
import com.gxks.lhs.security.JwtTokenProvider;
import com.gxks.lhs.constants.R;
import com.gxks.lhs.exception.ServiceException;
import com.gxks.lhs.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

/**
 * @author LuoHaisong
 */
@Api(tags = "demo测试模块")
@Slf4j
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired

    private IUserService userService;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    @Autowired
    private AuthenticationManager authenticationManager;


    @ApiOperation(value = "公开测试接口")
    @GetMapping("/any")
    public R any() {
        log.warn(">>>>>>>DEMO:ANY");
        return R.success(userService.list());
    }

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @ApiOperation(value = "公开测试接口")
    @GetMapping("/admin")
    public R AD() {
        log.warn(">>>>>>>DEMO:admin");
        return R.success(">>>>>>>DEMO:admin");
    }

    @PreAuthorize("hasAuthority('ROLE_USER')")
    @ApiOperation(value = "公开测试接口")
    @GetMapping("/user")
    public R use() {
        log.warn(">>>>>>>DEMO:user");
        return R.success(">>>>>>>DEMO:user");
    }

    @ApiOperation(value = "访问成功")
    @PostMapping("/ok")
    public R ok() {
        log.warn(">>>>>>>DEMO:OK");
        return R.success();
    }

    @ApiOperation(value = "业务错误")
    @PutMapping("/ser")
    public R serviceSerror() {
        log.warn(">>>>>>>DEMO:SERVICES_ERROR");
        throw new ServiceException("业务错误");
    }

    @ApiOperation(value = "系统错误")
    @DeleteMapping("/sys")
    public R systemSerror() {
        log.warn(">>>>>>>DEMO:SYSTEM_ERROR");
        int i = 1 / 0;
        return R.success();
    }

    @GetMapping("/userInfo")
    @PreAuthorize("hasAuthority('ROLE_USER')")
    public ResponseEntity<String> getUserInfo() {
        // 在这里，你可以直接使用 SecurityContextHolder.getContext().getAuthentication().getName() 获取用户名
        // ...

        return ResponseEntity.ok("User Info: " + SecurityContextHolder.getContext().getAuthentication().getName());
    }

//    @PostMapping("/login")
//    public ResponseEntity<?> login(@RequestBody Admin data) {
//        try {
//            String username = data.getUsername();
//            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, data.getPassword()));
//
//            String token = jwtTokenProvider.generateToken(username, "USER"); // You may customize roles based on your requirements
//
//            return ResponseEntity.ok(token);
//        } catch (AuthenticationException e) {
//            return ResponseEntity.status(401).body("Invalid credentials");
//        }
//    }

//    /**
//     * 登录接口
//     *
//     * @param data 登录信息
//     * @return 返回登录结果
//     */
//    @PostMapping("/login")
//    public ResponseEntity<?> login(@RequestBody Admin data) {
//        try {
//            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(data.getUsername(), data.getPassword()));
//            UserDetails userDetails = securityUserDetailsService.loadUserByUsername("Admin" + data.getUsername());
//            String token = jwtTokenProvider.generateToken(userDetails.getUsername(), "ADMIN");
//            return ResponseEntity.ok(token);
//        } catch (AuthenticationException e) {
//            return ResponseEntity.status(401).body("无效的凭证");
//        }
//    }
//
//    @PostMapping("/userLogin")
//    public ResponseEntity<?> userLogin(@RequestBody User user) {
//        try {
//            UserDetails userDetails = userService.getUserByUsername(user.getUsername());
//            String token = jwtTokenProvider.generateToken(userDetails.getUsername(), "USER");
//            return ResponseEntity.ok(token);
//        } catch (AuthenticationException e) {
//            return ResponseEntity.status(401).body("无效的凭证");
//        }
//    }

    @PostMapping("/admin/login")
    public ResponseEntity<?> adminLogin(@RequestBody LoginDTO loginRequest) {
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),
                        loginRequest.getPassword()
                )
        );
        log.warn(String.valueOf(authentication));

//        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtTokenProvider.generateAccessToken(authentication.getName(), authentication.getAuthorities().toString());
        return ResponseEntity.ok(jwt);
    }
}
